package com.tanavlog.web.service.impl;

import com.tanavlog.common.enums.RedisSaveHeader;
import com.tanavlog.common.enums.ResultCodeEnum;
import com.tanavlog.common.exception.BizException;
import com.tanavlog.common.service.MailService;
import com.tanavlog.common.utils.CodeGeneratorUtil;
import com.tanavlog.web.dto.request.RegistryUserInfoCheckDTO;
import com.tanavlog.web.dto.response.UserUniqueCheckResult;
import com.tanavlog.web.mapper.UserInfoMapper;
import com.tanavlog.web.properties.WebApplicationProperties;
import com.tanavlog.web.service.RegistryLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.Objects;
import java.util.Random;

/**
 * @author 枫花恋
 * @description 注册登录服务实现类
 * @since 2025/7/25 11:10
 */
@Service
public class RegistryLoginServiceImpl implements RegistryLoginService {
    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private RedisTemplate<String, String> stringRedisTemplate;

    @Autowired
    private MailService mailService;

    @Autowired
    private WebApplicationProperties webApplicationProperties;

    @Override
    public UserUniqueCheckResult checkUserInfo(RegistryUserInfoCheckDTO registryUserInfoCheckDTO) {
        UserUniqueCheckResult userUniqueCheckResult = new UserUniqueCheckResult();
        // 1.判断邮箱
        if (!Objects.isNull(userInfoMapper.getUserInfoByEmail(registryUserInfoCheckDTO.getEmail()))) {
            userUniqueCheckResult.setEmailExists(true);
        }
        // 2.判断用户名
        if (!Objects.isNull(userInfoMapper.getUserInfoByUsername(registryUserInfoCheckDTO.getUsername()))) {
            userUniqueCheckResult.setUsernameExists(true);
        }
        return userUniqueCheckResult;
    }

    @Override
    public Boolean sendVerifyCode(String email) {
        // 0. todo 如果redis有该邮箱的验证码，就返回操作频繁
        // 1. 生成验证码
        String verifyCode = CodeGeneratorUtil.getEmailVerifyCode();
        // 2. 往邮箱发送验证码
        mailService.sendSimpleMail(email, "验证码", verifyCode);
        // 3. 记录到redis中
        stringRedisTemplate.opsForValue().set(RedisSaveHeader.REGISTY.getKeyHead() + email, verifyCode, webApplicationProperties.getBusiness().getEmailVerifyCodeExp(), webApplicationProperties.getBusiness().getEmailVerifyCodeExpUnit());
        return true;
    }
}
